package se.sll.service.catalogue.notif.smtp;

import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Body;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultMessage;
import se.sll.service.catalogue.common.message.ExpiringCapacitiesNotification;
import se.sll.service.catalogue.common.property.CatalogProperties;

/**
 *
 * @author Jiri Uosukainen
 */
@Slf4j
public class SmtpSplitProcessor {
    
    
    public List<Message> splitMessage(@Body ExpiringCapacitiesNotification notification) throws Exception{
        
        log.info("SmtpSplitProcessor.splitMessage() : ENTER");
        List<Message> recipients = new ArrayList<>();
                
        if (notification != null) {
            log.info("SmtpSplitProcessor.splitMessage(): notification = {}", notification);
            
            List<String> emails = notification.getRecipients();
            
            StringBuilder messageBody = new StringBuilder(CatalogProperties.getProperty(CatalogProperties.NAME.NOTIFICATION_CAPACITY_SMTP_MESSAGE))
                    .append("<br/>")
                    .append("<a href="+CatalogProperties.getProperty(CatalogProperties.NAME.NOTIFICATION_CAPACITY_SMTP_LINK_URL_TO_GUI)+">"+CatalogProperties.getProperty(CatalogProperties.NAME.NOTIFICATION_CAPACITY_SMTP_LINK_NAME_TO_GUI)+"</a>");
            
            if (emails != null) {
                for (String address : emails) {
                    DefaultMessage message = new DefaultMessage();
                    message.setHeader("Content-Type", "text/html; charset=UTF-8");
                    message.setHeader("To", address);
                    message.setHeader("From", CatalogProperties.getProperty(CatalogProperties.NAME.NOTIFICATION_CAPACITY_SMTP_FROM));
                    message.setHeader("Subject", CatalogProperties.getProperty(CatalogProperties.NAME.NOTIFICATION_CAPACITY_SMTP_SUBJECT));
                    message.setBody(messageBody.toString());
                    recipients.add(message);
//                    log.info("SmtpSplitProcessor.splitMessage(): Created message {}", message);
                }
            }
        }
        else{
            throw new IllegalArgumentException("Invalid input: ExpiringCapacitiesNotification = null");
        }
        log.info("SmtpSplitProcessor.splitMessage() : EXIT");
        return recipients;
    }
}
